import { IPoint } from "@/models/gui";
import { IFn } from "@/models/math";
import * as jStat from 'jstat';

// 岭回归 矩阵运算
export function getRidgeRegressionFittingFn (cores: IFn[], points: IPoint[], a = 1): IFn {
  const n = cores.length;
  const m = points.length;
  const X: number[][] = [];
  for (let i = 0; i < m; i++) {
    X[i] = [];
    for (let j = 0; j < n; j++) {
      X[i][j] = cores[j](points[i].x);
    }
  }
  const Y = points.map(p => p.y);
  const XT: number[][] = jStat.transpose(X);
  const I: number[][] = jStat.identity(n);
  const YT = jStat.transpose(Y);
  const e1 = jStat.multiply(XT, X);
  const e2 = jStat.multiply(I, a);
  const e3 = jStat.add(e1, e2);
  const e4 = jStat.inv(e3);
  const e5 = jStat.multiply(e4, XT);
  const e6 = jStat.multiply(e5, YT);
  return (x) => {
    const y = jStat.multiply([cores.map(c => c(x))], e6);
    return y;
  };
}

